import {createContext, useReducer} from 'react';

const getInitState = () => ({
    business: null,
    businessList: [],
    project: null,
    projectList: [],
    path: null,
    pathList: [],
});

const reducer = (state, action) => {
    const {type, data} = action;
    const {
        businessList
    } = state;
    switch (type) {
        case 'changeBusinessList':
            return {
                ...state,
                businessList: data
            };
        case 'changeProjectList':
            return {
                ...state,
                projectList: data,
                path: null,
                pathList: []
            };
        case 'changePathList':
            if (Array.isArray(data)) {
                return {
                    ...state,
                    pathList: data,
                    path: null
                };
            }
            return {
                ...state,
                pathList: data.pathList,
                path: null
            };
        case 'changeBusiness':
            return {
                ...state,
                ...data,
                project: null,
                pathList: [],
                path: null,
            };
        case 'changeProject':
            return {
                ...state,
                ...data,
                path: null,
            };
        case 'changePath':
            return {
                ...state,
                ...data
            };
        case 'appendPath':
            return {
                ...state,
                pathList: [...new Set(state.pathList.concat(data))]
            };
        case 'reset':
            // 唯一不重置的是第一步的下拉
            return {
                ...getInitState(),
                businessList
            };
        default:
            return state;
    }
};

export default () => {
    const [state, dispatch] = useReducer(reducer, getInitState());
    return [state, dispatch];
};
